package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.ContactBean;
import com.bocai.dahuatech.Bean.FXShangBean;
import com.bocai.dahuatech.Bean.IndividualBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 经销商注册第一步
 */
public class RegistDistributorSecendActivity extends BaseActivity implements View.OnClickListener

{
    @Bind(R.id.btn_next)
    Button btnNext;
    @Bind(R.id.et_regist_secend_companyname)
    EditText etCompanyName;
    @Bind(R.id.et_regist_secend_money)
    EditText etMoney;
    @Bind(R.id.et_regist_secend_addr)
    EditText etAddr;
    @Bind(R.id.et_regist_secend_name)
    EditText etName;
    @Bind(R.id.et_regist_secend_phone)
    EditText etPhone;
    @Bind(R.id.et_regist_secend_email)
    EditText etEmail;
    @Bind(R.id.cb_regist_secend_agreement)
    CheckBox cbAgreement;
    @Bind(R.id.iv_regist_tip)
    ImageView ivTip;
    IndividualBean bean;
    String what;
    String Province="";
    String City="";
    String Area="";
    @Override
    protected int contentView()
    {
        return R.layout.activity_regist_distributor_secend;
    }
    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        bean= (IndividualBean) getIntent().getSerializableExtra("register");
        what=getIntent().getStringExtra("what");
        etAddr.setText(bean.getProvince()+" "+bean.getCity()+" "+bean.getArea());
        initToolbar(R.string.Sign);
        mToolbar.inflateMenu(R.menu.menu_next);
        getCustomer();
        initEvent();
    }

    /**
     * 初始化省市
     */
    private void getCustomer() {
        if(what.equals("regist")){
            Province=bean.getProvince();
            City=bean.getCity();
            Area=bean.getArea();
        }else{
            Province= SharePrefencesUtil.getProvince(this);
            City=SharePrefencesUtil.getCity(this);
            Area=SharePrefencesUtil.getArea(this);
        }
//        //根据省市获取签约代理商
//        getTestApi().getCustomer(Province,City)
////        getTestApi().getCustomer("浙江省","杭州市")
//                        .compose(this.<BaseBean>bindToLifecycle())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(observer);
    }

    @Override
    public void onEventMainThread(MainEvent event)
    {
        super.onEventMainThread(event);
        if("registisover".equals(event.msg))
        {
            finish();
        }
    }

    @Override
    protected void initEvent()
    {
        btnNext.setOnClickListener(this);
        ivTip.setOnClickListener(this);
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                next();
                return false;
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btn_next:
                next();
                break;
            case R.id.iv_regist_tip:
                /**
                 * 若没有分销商，点击查找联系人
                 */
                getTestApi().getMemberContact(Province,City)
                        .compose(this.<BaseBean>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BaseBean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("error",e.toString());
                                showToast(R.string.neterror);
                            }

                            @Override
                            public void onNext(BaseBean baseBean) {
                                if (baseBean.getReturnNo().equals("1"))
                                {
                                    String result=AESUtils.decode(baseBean.getContent());
                                    if(result!=null){
                                        result=start+result+end;
                                        Log.e("result",result);
                                        ContactBean contactBean=new Gson().fromJson(result,ContactBean.class);
                                        DialogUtil.dialogForOneButton(RegistDistributorSecendActivity.this,getResources().getString(R.string.pleasecontact)+contactBean.getContent().getFContact()+contactBean.getContent().getFMobelPhone()+getResources().getString(R.string.toconsulted) ,R.string.know);
                                    }
                                }
                            }
                        });

                break;
        }
    }

    private void next() {
        if(TextUtils.isEmpty(etCompanyName.getText().toString()))
        {
            showToast(R.string.agentnotnull);
        }else if (TextUtils.isEmpty(etMoney.getText().toString()))
        {
            showToast(R.string.signmoneynotnull);
        }else if (!etAddr.getText().toString().equals(bean.getAddress()))
        {
            showToast(R.string.addressfalse);
        }else if (TextUtils.isEmpty(etName.getText().toString()))
        {
            showToast(R.string.contactsnotnull);
        }else if (TextUtils.isEmpty(etPhone.getText().toString()))
        {
            showToast(R.string.telnumbernotnull);
        }else if (TextUtils.isEmpty(etEmail.getText().toString()))
        {
            showToast(R.string.mailboxnotnull);
        }else if (!cbAgreement.isChecked())
        {
            showToast(R.string.notsignagreement);
        }else
        {
            //检查用户输入的代理商是否存在
            checkCustomer();
//                    bean.setDistributor(etCompanyName.getText().toString());
//                    bean.setDistributorCode("");
//                    bean.setContractAmount(etMoney.getText().toString());
//                    bean.setContactor(etName.getText().toString());
//                    bean.setContactTel(etPhone.getText().toString());
//                    bean.setContactEmail(etEmail.getText().toString());
//                    Intent intent=new Intent(this,RegistDistributorThirdActivity.class);
//                    intent.putExtra("register",bean);
//                    intent.putExtra("what",what);
//                    startActivity(intent);
        }
    }

    /**
     * 检查代理商名称是否正确
     */
    private void checkCustomer() {
        Log.e("provice",Province);
        Log.e("city",City);
        getTestApi().checkCustomer(Province,Province+"-"+City,etCompanyName.getText().toString().trim())
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("error", e.toString());
                    }

                    @Override
                    public void onNext(BaseBean baseBean) {
                        Log.e("result", baseBean.getReturnInfo());
                        String result = AESUtils.decode(baseBean.getContent());//false  错误  true  正确
                        result = result.toLowerCase();
                        if ("true".equals(result)) {
                            bean.setDistributor(etCompanyName.getText().toString());
                            bean.setDistributorCode("");
                            bean.setContractAmount(etMoney.getText().toString());
                            bean.setContactor(etName.getText().toString());
                            bean.setContactTel(etPhone.getText().toString());
                            bean.setContactEmail(etEmail.getText().toString());
                            Intent intent = new Intent(RegistDistributorSecendActivity.this, RegistDistributorThirdActivity.class);
                            intent.putExtra("register", bean);
                            intent.putExtra("what", what);
                            startActivity(intent);
                        } else if ("false".equals(result)) {
                            showToast(R.string.agentfalse);
                        }
                    }
                });
    }

    FXShangBean fxShangBean;
    Observer<BaseBean> observer=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            if(baseBean.getReturnNo().equals("1"))
            {
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                fxShangBean=new Gson().fromJson(result,FXShangBean.class);
                if(fxShangBean.getContent().size()!=0)
                {
                    etCompanyName.setText(fxShangBean.getContent().get(0).getFCustomerName());
                }
            }else{
                showToast(baseBean.getReturnInfo());
            }
        }
    };
}
